package com.atguigu.blog.web;

import com.atguigu.blog.pojo.Article;
import com.atguigu.blog.pojo.ArticleComment;
import com.atguigu.blog.pojo.AuthUser;
import com.atguigu.blog.service.ArticleCommentService;
import com.atguigu.blog.service.ArticleService;
import com.atguigu.blog.service.LogInfoService;
import com.atguigu.blog.service.UserService;
import com.atguigu.blog.util.IdWorker;
import com.atguigu.blog.util.UserInfoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 网站首页
 */
@Controller
@RequestMapping("")
@Slf4j
public class IndexController {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleCommentService articleCommentService;

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/kk")
    public String kk(Map<String, Object> map) {
        List<Article> list = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            Article video=new Article();
            String numeric = RandomStringUtils.randomNumeric(4);
            video.setNum(numeric);
            list.add(video);
        }
        map.put("num", list);
        return "kkkkk/kkk";
    }

    @GetMapping("/random")
    @ResponseBody
    public String random() {
        String numeric = RandomStringUtils.randomNumeric(6);
        return numeric;
    }

    /**
     * 首页
     * @param map
     * @return
     */
    @RequestMapping(value = {"/index", "/", "/index.html"}, method = {RequestMethod.GET, RequestMethod.POST})
    public String index(Map<String, Object> map,HttpServletRequest request, Authentication authentication, HttpSession session) {
        logInfoService.saveLogInfo(request, "网站首页");

        String username = UserInfoUtil.getUsername(authentication);
        List<Article> list = articleService.findAll();
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        AuthUser user = userService.getOne(queryWrapper);

        //String list1 = (String) redisTemplate.opsForValue().get("list");
        //redisTemplate.opsForValue().set("list", list);
        if (user!=null) {
            String fullname = user.getFullname();
            session.setAttribute("fullname", fullname);
            map.put("fullname", fullname);
        }
        map.put("list", list);
        session.setAttribute("name", username);
        log.debug("username"+username);
        map.put("name", username);
        return "index";
    }

    /**
     * 文章详情页
     * @param id id
     * @param map map
     * @return 返回页面
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Map<String, Object> map, HttpServletRequest request) {
        Article article = articleService.findById(id);
        List<ArticleComment> comment = articleCommentService.findById(id);
        article.setArticleComment(comment);
        map.put("article", article);
        logInfoService.saveLogInfo(request, "文章详情页-"+article.getArticleName());
        return "details";
    }

    /**
     * 文章评论
     * @param id 文章id
     * @return
     */
    @GetMapping("/comment/{id}")
    public String comment(@PathVariable("id") String id, Map<String, Object> map) {
        Article article = articleService.findById(id);
        List<ArticleComment> comment = articleCommentService.findById(id);
        article.setArticleComment(comment);
        map.put("article", article);
        return "comment";
    }

    /**
     * 写文章评论
     * ID 文章ID
     */
    @GetMapping("/articleComment/{artId}")
    public String articleComment(@PathVariable("artId") String artId,ArticleComment articleComment, Authentication authentication) {
        if (authentication==null) {
            return "login";
        }
        String username = UserInfoUtil.getUsername(authentication);
        articleComment.setCommentUsername(username);
        articleComment.setArticleId(artId);
        articleComment.setId(idWorker.nextId()+"");
        articleComment.setCreateDate(new Date());
        articleComment.setCommentZan("0");
        articleCommentService.save(articleComment);

        Article article = articleService.findById(artId);
        Integer commentCount = Integer.parseInt(article.getCommentCount());// 评论数
        article.setCommentCount((commentCount+1)+"");
        articleService.updateById(article);
        return "redirect:/detail/"+artId;
    }

    /**
     * 文章评论点赞
     */
    @GetMapping("/articleCommentZan/{commentId}")
    public String articleCommentZan(@PathVariable("commentId") String commentId) {
        ArticleComment articleComment = articleCommentService.getById(commentId);
        int i = Integer.parseInt(articleComment.getCommentZan());
        articleComment.setCommentZan((i+1)+"");
        articleCommentService.updateById(articleComment);
        return "redirect:/detail/"+articleComment.getArticleId();
    }

    /**
     * 文章评论点赞
     */
    @GetMapping("/articleZan/{id}")
    public String articleZan(@PathVariable("id") String id) {
        Article article = articleService.getById(id);
        int i = Integer.parseInt(article.getCommendCount());
        article.setCommendCount((i+1)+"");
        articleService.updateById(article);
        return "redirect:/index";
    }

    /**
     * 创作页
     * @return
     */
    @GetMapping("/write")
    public String write(Map<String, Object> map, Authentication authentication) {
        String username = UserInfoUtil.getUsername(authentication);
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        AuthUser user = userService.getOne(queryWrapper);
        if (user!=null) {
            String fullname = user.getFullname();
            map.put("fullname", fullname);
        }
        log.debug("username"+username);
        map.put("name", username);
        return "write";
    }

    @PostMapping("/writeAdd")
    public String writeAdd(Article article, Authentication authentication, HttpServletRequest request) {
        if (authentication==null) {
            return "login";
        }
        String name = authentication.getName();
        log.debug("当前登录用户", name);
        article.setUsername(name);
        article.setId(idWorker.nextId()+"");
        article.setIsHome("Y");
        article.setArticleStatus(0);
        article.setReadCount("0");
        article.setCommendCount("0");
        article.setCommentCount("0");
        article.setReadCount("0");
        article.setCreateDate(new Date());
        article.setUpdateDate(new Date());
        boolean save = articleService.save(article);
        if (save) {
            logInfoService.saveLogInfo(request, "创作文章-" + article.getArticleName());
        }
        return "write";
    }

}
